package com.ken.apollo.controller;

import com.ken.apollo.commons.result.R;
import com.ken.apollo.commons.utils.MailContentUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.web.bind.annotation.*;

import jakarta.mail.internet.MimeMessage;

/**
 * 邮件测试控制器
 * 用于测试HTML邮件发送功能
 *
 * @author Ken
 * @since 2025-08-25
 */
@RestController
@RequestMapping("/api/mail/test")
@Slf4j
public class MailTestController {

    @Autowired
    private JavaMailSender javaMailSender;

    @Autowired
    private MailContentUtils mailContentUtils;

    /**
     * 发送HTML测试邮件
     */
    @PostMapping("/html")
    public R<String> sendHtmlTestMail(@RequestParam String toEmail, 
                                      @RequestParam(defaultValue = "HTML邮件测试") String subject,
                                      @RequestParam(required = false) String content) {
        try {
            // 如果没有提供内容，使用默认的HTML内容
            if (content == null || content.trim().isEmpty()) {
                content = createTestHtmlContent();
            }

            MimeMessage message = javaMailSender.createMimeMessage();
            // 不使用multipart模式，只发送HTML内容
            MimeMessageHelper helper = new MimeMessageHelper(message, false, "UTF-8");

            helper.setFrom("verygoodwlk@126.com", "Apollo系统");
            helper.setTo(toEmail);
            helper.setSubject(subject);
            
            // 处理邮件内容，将相对路径转换为绝对路径
            String processedContent = mailContentUtils.processMailContent(content);
            
            // 设置HTML内容
            helper.setText(processedContent, true);

            javaMailSender.send(message);
            
            log.info("【HTML测试邮件发送成功】收件人：{}, 主题：{}", toEmail, subject);
            
            return R.success("HTML邮件发送成功！");
            
        } catch (Exception e) {
            log.error("【HTML测试邮件发送失败】收件人：{}, 错误：{}", toEmail, e.getMessage());
            return R.fail("邮件发送失败：" + e.getMessage());
        }
    }

    /**
     * 发送带附件的HTML测试邮件
     */
    @PostMapping("/html-with-attachment")
    public R<String> sendHtmlTestMailWithAttachment(@RequestParam String toEmail, 
                                                    @RequestParam(defaultValue = "HTML邮件测试(带附件)") String subject,
                                                    @RequestParam(required = false) String content) {
        try {
            // 如果没有提供内容，使用默认的HTML内容
            if (content == null || content.trim().isEmpty()) {
                content = createTestHtmlContent();
            }

            MimeMessage message = javaMailSender.createMimeMessage();
            // 使用multipart模式支持附件
            MimeMessageHelper helper = new MimeMessageHelper(message, true, "UTF-8");

            helper.setFrom("verygoodwlk@126.com", "Apollo系统");
            helper.setTo(toEmail);
            helper.setSubject(subject);
            
            // 处理邮件内容，将相对路径转换为绝对路径
            String processedContent = mailContentUtils.processMailContent(content);
            
            // 设置HTML内容
            helper.setText(processedContent, true);
            
            // 添加一个文本测试附件
            String testContent = "这是一个测试附件。\n\n生成时间：" + java.time.LocalDateTime.now();
            helper.addAttachment("测试附件.txt", new org.springframework.core.io.ByteArrayResource(testContent.getBytes("UTF-8")));

            javaMailSender.send(message);
            
            log.info("【带附件HTML测试邮件发送成功】收件人：{}, 主题：{}", toEmail, subject);
            
            return R.success("带附件HTML邮件发送成功！");
            
        } catch (Exception e) {
            log.error("【带附件HTML测试邮件发送失败】收件人：{}, 错误：{}", toEmail, e.getMessage());
            return R.fail("邮件发送失败：" + e.getMessage());
        }
    }

    /**
     * 创建测试用的HTML内容
     */
    private String createTestHtmlContent() {
        return """
            <!DOCTYPE html>
            <html>
            <head>
                <meta charset="UTF-8">
                <title>HTML邮件测试</title>
                <style>
                    body { font-family: Arial, sans-serif; margin: 20px; }
                    .header { background-color: #4CAF50; color: white; padding: 20px; text-align: center; }
                    .content { padding: 20px; border: 1px solid #ddd; }
                    .highlight { background-color: #ffeb3b; padding: 5px; }
                    .footer { background-color: #f1f1f1; padding: 10px; text-align: center; font-size: 12px; }
                    table { border-collapse: collapse; width: 100%; margin: 20px 0; }
                    table, th, td { border: 1px solid #ddd; }
                    th, td { padding: 8px; text-align: left; }
                    th { background-color: #f2f2f2; }
                </style>
            </head>
            <body>
                <div class="header">
                    <h1>Apollo系统 - HTML邮件测试</h1>
                </div>
                
                <div class="content">
                    <h2>这是一封HTML格式的测试邮件</h2>
                    
                    <p>如果您能看到<strong>粗体文字</strong>、<em>斜体文字</em>和<span class="highlight">高亮背景</span>，说明HTML邮件功能正常。</p>
                    
                    <h3>功能测试项目：</h3>
                    <ul>
                        <li>✓ 基本HTML标签支持</li>
                        <li>✓ CSS样式支持</li>
                        <li>✓ 中文字符显示</li>
                        <li>✓ 表格显示</li>
                    </ul>
                    
                    <h3>测试表格：</h3>
                    <table>
                        <tr>
                            <th>项目</th>
                            <th>状态</th>
                            <th>说明</th>
                        </tr>
                        <tr>
                            <td>HTML标签</td>
                            <td style="color: green;">正常</td>
                            <td>支持基本HTML标签</td>
                        </tr>
                        <tr>
                            <td>CSS样式</td>
                            <td style="color: green;">正常</td>
                            <td>支持内联CSS样式</td>
                        </tr>
                        <tr>
                            <td>中文字符</td>
                            <td style="color: green;">正常</td>
                            <td>正确显示中文内容</td>
                        </tr>
                    </table>
                    
                    <p style="color: #666; font-size: 14px;">
                        <strong>测试时间：</strong> """ + java.time.LocalDateTime.now() + """
                    </p>
                </div>
                
                <div class="footer">
                    <p>此邮件由Apollo系统自动发送，如有问题请联系系统管理员。</p>
                </div>
            </body>
            </html>
            """;
    }

    /**
     * 测试邮件内容处理功能
     */
    @PostMapping("/content-process")
    public R<String> testMailContentProcess(@RequestParam String htmlContent) {
        try {
            String processedContent = mailContentUtils.processMailContent(htmlContent);
            
            log.info("【邮件内容处理测试】原始内容长度：{}, 处理后长度：{}", 
                htmlContent.length(), processedContent.length());
            
            return R.success(processedContent);
            
        } catch (Exception e) {
            log.error("【邮件内容处理测试失败】错误：{}", e.getMessage());
            return R.fail("内容处理失败：" + e.getMessage());
        }
    }

    /**
     * 获取当前基础URL配置
     */
    @GetMapping("/base-url")
    public R<String> getBaseUrl() {
        try {
            String baseUrl = mailContentUtils.getBaseUrl();
            return R.success(baseUrl);
        } catch (Exception e) {
            return R.fail("获取基础URL失败：" + e.getMessage());
        }
    }
}